<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { postLinkage, putLinkage } from '#/api/portal/linkage';

const [Form, FormApi] = useVbenForm({
  handleSubmit: onSubmit,
  showDefaultActions: false,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '名称',
      rules: 'required',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      dependencies: {
        trigger: (values, form) => {
          if (values.name) {
            const code = pinyin(values.name, {
              pattern: 'first',
              toneType: 'none',
            }).replaceAll(/\s+/g, '');
            form.setFieldValue('code', code);
          }
        },
        disabled(values) {
          return !!values.id;
        },
        triggerFields: ['id', 'name'],
      },
      fieldName: 'code',
      label: '标识',
      rules: 'required',
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
});

const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onConfirm: async () => {
    await FormApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = formModalApi.getData();
      if (values) {
        FormApi.setValues(values);
      }
    }
  },
});

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);
    formModalApi.setData({ isUpdata: true });
    formModalApi.close();
  }
  if (values.id) {
    const { msg } = await putLinkage(values);
    showMsg(msg);
  } else {
    const { msg } = await postLinkage(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal class="w-3/5"> <Form /> </Modal>
</template>

<style lang="scss" scoped></style>
